package org.springframework.ai.mcp.samples.client;

import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallback;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
 
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class McpClientConfig {


    @Bean
    public McpSyncClient getMcpSyncClient() {
        HttpClient.Builder httpClientBuilder = HttpClient.newBuilder();
        httpClientBuilder.connectTimeout(Duration.ofSeconds(5));
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder();
        requestBuilder.header("Authorization","Bearer secret123");
        HttpClientSseClientTransport transport = HttpClientSseClientTransport.builder("http://localhost:8080")
                .requestBuilder(requestBuilder)
                .sseEndpoint("/weather/mcp/sse")
                .clientBuilder(httpClientBuilder).build();

        McpSyncClient mcpSyncClient = McpClient.sync(transport).requestTimeout(Duration.ofSeconds(10)).build();
        mcpSyncClient.initialize();
        return mcpSyncClient;
    }


    @Bean
    public List<SyncMcpToolCallback> getSyncMcpToolCallback(McpSyncClient mcpSyncClient) {
        List<SyncMcpToolCallback> list = mcpSyncClient
                .listTools()
                .tools()
                .stream()
                .map(tool -> new SyncMcpToolCallback(mcpSyncClient, tool))
                .toList();
        return list;
    }

    @Bean
    public String systemPrompt(McpSyncClient client){
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("user","张三");
        McpSchema.GetPromptRequest getPromptRequest = new McpSchema.GetPromptRequest("weather",arguments);
        McpSchema.GetPromptResult prompt = client.getPrompt(getPromptRequest);
        List<McpSchema.PromptMessage> messages = prompt.messages();
        McpSchema.PromptMessage promptMessage = messages.get(0);
        McpSchema.Content content = promptMessage.content();
        return content.toString();
    }

    @Bean
    public ChatClient chatClient(ChatClient.Builder builder,
                                 List<SyncMcpToolCallback> syncMcpToolCallbacks) {
        return builder.defaultToolCallbacks(syncMcpToolCallbacks.toArray(new ToolCallback[0]))
                .build();
    }

}
